<template>
    <div>
        <el-affix position="bottom" :offset="20" class="floating-affix">
            <el-button type="primary" @click="changeMouseCursor"
                :class="isSelected ? 'selected-btn' : 'unselected-btn'"></el-button>
        </el-affix>
    </div>
    <div id="container" @mousedown="handleMouseLeftDown" @mouseenter="handleMouseEnter" @mouseup="handleMouseLeftUp"
        @mouseleave="handleMouseLeave">
    </div>
</template>

<script setup lang="ts" name="InfiniteCanvas">
import Konva from 'konva';
import { onMounted, ref } from 'vue';
import { TransformerManager } from '@/canvas/handler/TransformerManager';
import { ShapesManager } from '@/canvas/handler/ShapesManager';
import { MouseStyle, CursorStyle } from '@/utils/MouseStyle';
import { KeyListener } from '@/utils/KeyListener';

const isSelected = ref(false);

/**
 * 点击后切换拖拽画布和选择图形
 */
const changeMouseCursor = () => {
    isSelected.value = !isSelected.value;
    stage.draggable(isSelected.value);
}

/**
 * 处理鼠标进入画布时样式
 */
const handleMouseEnter = () => {
    if (isSelected.value)
    MouseStyle.setCursor(CursorStyle.Grab);
    else
    MouseStyle.setCursor(CursorStyle.Default);
}

/**
 * 处理鼠标进入画布且按下时样式
 */
const handleMouseLeftDown = () => {
    if (isSelected.value) {
        MouseStyle.setCursor(CursorStyle.Grabbing);
    }
};

/**
 * 鼠标松开时样式
 */
const handleMouseLeftUp = () => {
    if (isSelected.value)
    MouseStyle.setCursor(CursorStyle.Grab);
};

/**
 * 鼠标离开画布时样式重置
 */
const handleMouseLeave = () => {
    MouseStyle.setCursor(CursorStyle.Default);
}

const WIDTH = 3000;
const HEIGHT = 3000;
let stage: Konva.Stage;
onMounted(() => {
    stage = new Konva.Stage({
        container: 'container',
        width: WIDTH,
        height: HEIGHT,
    });
    const layer = new Konva.Layer();
    stage.add(layer);
    // 初始化管理器
    const transformerManager = new TransformerManager(layer);
    const ctrlKeyListener = new KeyListener();
    // 创建 ShapesManager 实例
    const shapesManager = new ShapesManager(layer, stage, transformerManager, ctrlKeyListener);
    shapesManager.createShape();
});

</script>

<style scoped>
.selected-btn {
    background-color: var(--button-selected-color);
    box-shadow: 0px 4px 10px var(--button-shadow-color);
    color: white;
}

.unselected-btn {
    background-color: var(--button-unselected-color);
    box-shadow: 0px 4px 10px var(--button-shadow-color);
}

.floating-affix {
    position: fixed;
    right: 20px;
    z-index: 1000;
}

#container {
    margin: 0;
    padding: 0;
    background-color: #ffffff;
    height: 100%;
    overflow: auto;
}
</style>